<template>
  <ProCard
    title="网络状态监控"
    :show-refresh="true"
    :refreshing="refreshing"
    class="network-status-card"
    @refresh="handleRefresh"
  >
    <template #extra>
      <a-space>
        <a-select
          v-model:value="timeRange"
          size="small"
          style="width: 120px"
          @change="handleTimeRangeChange"
        >
          <a-select-option value="1h">近1小时</a-select-option>
          <a-select-option value="6h">近6小时</a-select-option>
          <a-select-option value="24h">近24小时</a-select-option>
          <a-select-option value="7d">近7天</a-select-option>
        </a-select>
        <a-button
          type="text"
          size="small"
          :icon="h(SettingOutlined)"
          @click="showSettings = true"
        />
      </a-space>
    </template>

    <div class="network-status-content">
      <!-- 整体健康状态 -->
      <div class="health-overview">
        <a-row :gutter="16">
          <a-col :span="6">
            <div class="health-item">
              <div class="health-icon" :class="getHealthClass(networkHealth.overall)">
                <component :is="getHealthIcon(networkHealth.overall)" />
              </div>
              <div class="health-info">
                <div class="health-label">整体健康</div>
                <div class="health-value">{{ getHealthLabel(networkHealth.overall) }}</div>
              </div>
            </div>
          </a-col>
          <a-col :span="6">
            <div class="health-item">
              <a-statistic
                title="活跃节点"
                :value="networkStats.activeNodes"
                :value-style="{ color: '#52c41a', fontSize: '20px' }"
              />
            </div>
          </a-col>
          <a-col :span="6">
            <div class="health-item">
              <a-statistic
                title="连接数"
                :value="networkStats.connections"
                :value-style="{ color: '#1890ff', fontSize: '20px' }"
              />
            </div>
          </a-col>
          <a-col :span="6">
            <div class="health-item">
              <a-statistic
                title="消息吞吐"
                :value="networkStats.messageRate"
                suffix="/s"
                :value-style="{ color: '#722ed1', fontSize: '20px' }"
              />
            </div>
          </a-col>
        </a-row>
      </div>

      <!-- 详细指标 -->
      <div class="metrics-detail">
        <a-row :gutter="16">
          <a-col :span="12">
            <div class="metric-item">
              <div class="metric-header">
                <span class="metric-title">网络延迟</span>
                <a-tag :color="getLatencyColor(networkMetrics.latency)">
                  {{ networkMetrics.latency }}ms
                </a-tag>
              </div>
              <a-progress
                :percent="getLatencyPercent(networkMetrics.latency)"
                :stroke-color="getLatencyColor(networkMetrics.latency)"
                :show-info="false"
                size="small"
              />
            </div>
          </a-col>
          <a-col :span="12">
            <div class="metric-item">
              <div class="metric-header">
                <span class="metric-title">带宽利用率</span>
                <a-tag :color="getBandwidthColor(networkMetrics.bandwidth)">
                  {{ networkMetrics.bandwidth }}%
                </a-tag>
              </div>
              <a-progress
                :percent="networkMetrics.bandwidth"
                :stroke-color="getBandwidthColor(networkMetrics.bandwidth)"
                :show-info="false"
                size="small"
              />
            </div>
          </a-col>
        </a-row>

        <a-row :gutter="16" style="margin-top: 16px">
          <a-col :span="12">
            <div class="metric-item">
              <div class="metric-header">
                <span class="metric-title">错误率</span>
                <a-tag :color="getErrorRateColor(networkMetrics.errorRate)">
                  {{ networkMetrics.errorRate }}%
                </a-tag>
              </div>
              <a-progress
                :percent="networkMetrics.errorRate"
                :stroke-color="getErrorRateColor(networkMetrics.errorRate)"
                :show-info="false"
                size="small"
              />
            </div>
          </a-col>
          <a-col :span="12">
            <div class="metric-item">
              <div class="metric-header">
                <span class="metric-title">负载均衡</span>
                <a-tag :color="getLoadBalanceColor(networkMetrics.loadBalance)">
                  {{ getLoadBalanceLabel(networkMetrics.loadBalance) }}
                </a-tag>
              </div>
              <a-progress
                :percent="networkMetrics.loadBalance"
                :stroke-color="getLoadBalanceColor(networkMetrics.loadBalance)"
                :show-info="false"
                size="small"
              />
            </div>
          </a-col>
        </a-row>
      </div>

      <!-- 告警信息 -->
      <div v-if="alerts.length > 0" class="alerts-section">
        <h4>
          <exclamation-circle-outlined style="color: #faad14; margin-right: 8px" />
          告警信息
        </h4>
        <div class="alerts-list">
          <a-alert
            v-for="alert in alerts.slice(0, 3)"
            :key="alert.id"
            :type="alert.level"
            :message="alert.message"
            :description="alert.description"
            :show-icon="true"
            :closable="true"
            style="margin-bottom: 8px"
            @close="handleAlertClose(alert.id)"
          />
          <a-button
            v-if="alerts.length > 3"
            type="link"
            size="small"
            @click="showAllAlerts = true"
          >
            查看全部 {{ alerts.length }} 条告警
          </a-button>
        </div>
      </div>

      <!-- 趋势图表 -->
      <div class="trend-chart">
        <h4>网络趋势</h4>
        <div class="chart-container" style="height: 200px">
          <slot name="chart">
            <!-- 这里可以集成 ECharts 或其他图表库 -->
            <div class="chart-placeholder">
              <line-chart-outlined style="font-size: 48px; color: #d9d9d9" />
              <p style="color: #999; margin-top: 16px">趋势图表</p>
            </div>
          </slot>
        </div>
      </div>
    </div>

    <!-- 设置弹窗 -->
    <a-modal
      v-model:open="showSettings"
      title="网络监控设置"
      :width="500"
      @ok="handleSettingsOk"
    >
      <a-form :model="settings" layout="vertical">
        <a-form-item label="刷新间隔">
          <a-select v-model:value="settings.refreshInterval">
            <a-select-option :value="5">5秒</a-select-option>
            <a-select-option :value="10">10秒</a-select-option>
            <a-select-option :value="30">30秒</a-select-option>
            <a-select-option :value="60">1分钟</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="告警阈值">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-input-number
                v-model:value="settings.latencyThreshold"
                :min="0"
                :max="1000"
                addon-after="ms"
                placeholder="延迟阈值"
              />
            </a-col>
            <a-col :span="12">
              <a-input-number
                v-model:value="settings.errorRateThreshold"
                :min="0"
                :max="100"
                addon-after="%"
                placeholder="错误率阈值"
              />
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item label="监控项目">
          <a-checkbox-group v-model:value="settings.monitorItems">
            <a-checkbox value="latency">网络延迟</a-checkbox>
            <a-checkbox value="bandwidth">带宽利用率</a-checkbox>
            <a-checkbox value="errorRate">错误率</a-checkbox>
            <a-checkbox value="loadBalance">负载均衡</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 全部告警弹窗 -->
    <a-modal
      v-model:open="showAllAlerts"
      title="全部告警"
      :width="800"
      :footer="null"
    >
      <div class="all-alerts-list">
        <a-alert
          v-for="alert in alerts"
          :key="alert.id"
          :type="alert.level"
          :message="alert.message"
          :description="alert.description"
          :show-icon="true"
          :closable="true"
          style="margin-bottom: 8px"
          @close="handleAlertClose(alert.id)"
        />
      </div>
    </a-modal>
  </ProCard>
</template>

<script setup lang="ts">
import { ref, reactive, h, onMounted, onUnmounted } from 'vue'
import { ProCard } from '../Pro'
import {
  SettingOutlined,
  ExclamationCircleOutlined,
  LineChartOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons-vue'

interface NetworkHealth {
  overall: 'healthy' | 'warning' | 'critical'
}

interface NetworkStats {
  activeNodes: number
  connections: number
  messageRate: number
}

interface NetworkMetrics {
  latency: number
  bandwidth: number
  errorRate: number
  loadBalance: number
}

interface Alert {
  id: string
  level: 'success' | 'info' | 'warning' | 'error'
  message: string
  description: string
  timestamp: string
}

interface NetworkStatusCardProps {
  networkHealth?: NetworkHealth
  networkStats?: NetworkStats
  networkMetrics?: NetworkMetrics
  alerts?: Alert[]
  refreshing?: boolean
}

const props = withDefaults(defineProps<NetworkStatusCardProps>(), {
  networkHealth: () => ({ overall: 'healthy' }),
  networkStats: () => ({ activeNodes: 0, connections: 0, messageRate: 0 }),
  networkMetrics: () => ({ latency: 0, bandwidth: 0, errorRate: 0, loadBalance: 0 }),
  alerts: () => [],
  refreshing: false,
})

const emit = defineEmits<{
  refresh: []
  timeRangeChange: [range: string]
  settingsChange: [settings: any]
}>()

// 响应式数据
const timeRange = ref('1h')
const showSettings = ref(false)
const showAllAlerts = ref(false)
const refreshTimer = ref<number>()

const settings = reactive({
  refreshInterval: 10,
  latencyThreshold: 100,
  errorRateThreshold: 5,
  monitorItems: ['latency', 'bandwidth', 'errorRate', 'loadBalance'],
})

// 健康状态相关方法
const getHealthClass = (health: string) => {
  return {
    'health-healthy': health === 'healthy',
    'health-warning': health === 'warning',
    'health-critical': health === 'critical',
  }
}

const getHealthIcon = (health: string) => {
  const iconMap = {
    healthy: CheckCircleOutlined,
    warning: WarningOutlined,
    critical: CloseCircleOutlined,
  }
  return iconMap[health as keyof typeof iconMap] || CheckCircleOutlined
}

const getHealthLabel = (health: string) => {
  const labelMap = {
    healthy: '良好',
    warning: '警告',
    critical: '严重',
  }
  return labelMap[health as keyof typeof labelMap] || '未知'
}

// 指标颜色相关方法
const getLatencyColor = (latency: number) => {
  if (latency < 50) return 'green'
  if (latency < 100) return 'orange'
  return 'red'
}

const getLatencyPercent = (latency: number) => {
  return Math.min((latency / 200) * 100, 100)
}

const getBandwidthColor = (bandwidth: number) => {
  if (bandwidth < 70) return 'green'
  if (bandwidth < 90) return 'orange'
  return 'red'
}

const getErrorRateColor = (errorRate: number) => {
  if (errorRate < 1) return 'green'
  if (errorRate < 5) return 'orange'
  return 'red'
}

const getLoadBalanceColor = (loadBalance: number) => {
  if (loadBalance > 80) return 'green'
  if (loadBalance > 60) return 'orange'
  return 'red'
}

const getLoadBalanceLabel = (loadBalance: number) => {
  if (loadBalance > 80) return '良好'
  if (loadBalance > 60) return '一般'
  return '较差'
}

// 事件处理
const handleRefresh = () => {
  emit('refresh')
}

const handleTimeRangeChange = (range: string) => {
  emit('timeRangeChange', range)
}

const handleSettingsOk = () => {
  showSettings.value = false
  emit('settingsChange', { ...settings })
  
  // 重新设置定时器
  setupRefreshTimer()
}

const handleAlertClose = (alertId: string) => {
  // 这里可以调用API关闭告警
  console.log('关闭告警:', alertId)
}

// 定时刷新
const setupRefreshTimer = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
  }
  
  refreshTimer.value = window.setInterval(() => {
    handleRefresh()
  }, settings.refreshInterval * 1000)
}

// 生命周期
onMounted(() => {
  setupRefreshTimer()
})

onUnmounted(() => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
  }
})
</script>

<style scoped>
.network-status-card {
  height: 100%;
}

.network-status-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.health-overview {
  background: #fafafa;
  padding: 16px;
  border-radius: 8px;
}

.health-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.health-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.health-icon.health-healthy {
  background: #f6ffed;
  color: #52c41a;
}

.health-icon.health-warning {
  background: #fffbe6;
  color: #faad14;
}

.health-icon.health-critical {
  background: #fff2f0;
  color: #ff4d4f;
}

.health-info {
  flex: 1;
}

.health-label {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  margin-bottom: 4px;
}

.health-value {
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.metrics-detail {
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.metric-item {
  margin-bottom: 8px;
}

.metric-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.metric-title {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}

.alerts-section h4,
.trend-chart h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.alerts-list {
  max-height: 200px;
  overflow-y: auto;
}

.chart-container {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
}

.all-alerts-list {
  max-height: 400px;
  overflow-y: auto;
}

/* 暗黑模式适配 */
[data-theme="dark"] .health-overview,
[data-theme="dark"] .metrics-detail {
  background: rgba(255, 255, 255, 0.04);
  border-color: #303030;
}

[data-theme="dark"] .health-label {
  color: rgba(255, 255, 255, 0.45);
}

[data-theme="dark"] .health-value {
  color: rgba(255, 255, 255, 0.85);
}

[data-theme="dark"] .metric-title {
  color: rgba(255, 255, 255, 0.65);
}

[data-theme="dark"] .alerts-section h4,
[data-theme="dark"] .trend-chart h4 {
  color: rgba(255, 255, 255, 0.85);
}

[data-theme="dark"] .chart-container {
  border-color: #303030;
  background: rgba(255, 255, 255, 0.02);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .health-overview {
    padding: 12px;
  }
  
  .health-item {
    flex-direction: column;
    text-align: center;
    gap: 8px;
  }
  
  .metrics-detail {
    padding: 12px;
  }
  
  .chart-container {
    height: 150px !important;
  }
}
</style>